#include"EventReceiver.h"
EventReceiver::OnEvent(const irr::SEvent &event)
{
		if (event.EventType == irr::EET_KEY_INPUT_EVENT)
		{
			KeyIsDown[event.KeyInput.Key] = event.KeyInput.PressedDown;
			return false;
		}
		if (event.EventType == irr::EET_MOUSE_INPUT_EVENT)
		{
			switch(event.MouseInput.Event)
			{
			case EMIE_LMOUSE_PRESSED_DOWN:
				MouseState.LeftButtonDown = true;
				break;

			case EMIE_LMOUSE_LEFT_UP:
				MouseState.LeftButtonDown = false;
				break;

			case EMIE_MOUSE_MOVED:
				MouseState.Position.X = event.MouseInput.X;
				MouseState.Position.Y = event.MouseInput.Y;
				break;

			default:
				// We won't use the wheel
				break;
			}
		}

		/*if (event.EventType == irr::EET_KEY_INPUT_EVENT)
		{
			KeyIsDown[event.KeyInput.Key] = event.KeyInput.PressedDown;
			return false;
		}*/
		if (event.EventType == EET_GUI_EVENT)
		{
			s32 id = event.GUIEvent.Caller->getID();
			IGUIEnvironment* env = Context.device->getGUIEnvironment();

			switch(event.GUIEvent.EventType)
			{
			case EGET_MENU_ITEM_SELECTED:
				OnMenuItemSelected((IGUIContextMenu*)event.GUIEvent.Caller);
				break;

			case EGET_SCROLL_BAR_CHANGED:
				if (id == GUI_ID_TRANSPARENCY_SCROLL_BAR)
				{
					s32 pos = ((IGUIScrollBar*)event.GUIEvent.Caller)->getPos();

					for (u32 i=0; i<EGDC_COUNT ; ++i)
					{
						SColor col = env->getSkin()->getColor((EGUI_DEFAULT_COLOR)i);
						col.setAlpha(pos);
						env->getSkin()->setColor((EGUI_DEFAULT_COLOR)i, col);
					}
				}
				if(id == GUI_ID_COLOR_SCROLL_BAR_RED)
				{
					s32 pos = ((IGUIScrollBar*)event.GUIEvent.Caller)->getPos();

					SColor col = env->getSkin()->getColor((EGUI_DEFAULT_COLOR)0);
					col.setRed(pos);
					env->getSkin()->setColor((EGUI_DEFAULT_COLOR)0,col);
				}
				if(id == GUI_ID_COLOR_SCROLL_BAR_GREEN)
				{
					s32 pos = ((IGUIScrollBar*)event.GUIEvent.Caller)->getPos();

					SColor col = env->getSkin()->getColor((EGUI_DEFAULT_COLOR)0);
					col.setGreen(pos);
					env->getSkin()->setColor((EGUI_DEFAULT_COLOR)0,col);
				}
				if(id == GUI_ID_COLOR_SCROLL_BAR_BLUE)
				{
					s32 pos = ((IGUIScrollBar*)event.GUIEvent.Caller)->getPos();

					SColor col = env->getSkin()->getColor((EGUI_DEFAULT_COLOR)0);
					col.setBlue(pos);
					env->getSkin()->setColor((EGUI_DEFAULT_COLOR)0,col);
				}
				if(id == GUI_ID_BACKGROUND_COLOR_BAR)
				{
					s32 pos = ((IGUIScrollBar*)event.GUIEvent.Caller)->getPos();

					SColor col;
				}
				break;


			case EGET_BUTTON_CLICKED:
				switch(id)
				{
				case GUI_ID_BUTTON_ONLINE_GAME_SIDE_BLACK:
					BlackSide = true;
					break;
				case GUI_ID_BUTTON_CLOSE_CONTROL_HELP:
					closeControlHelp();
					break;
				case GUI_ID_BUTTON_END_GAME:
					StartNewGame = false;
					PlayerEndGame = true;
					SaveGameSubWindow();
					break;
				case GUI_ID_BUTTON_GAME_LEVEL_ONE:
					Context.device->getGUIEnvironment()->addMessageBox(L"warning",
						L"Start Game Level One!",false);
					chooseLevelOne();
					break;
				case GUI_ID_BUTTON_GAME_LEVEL_TWO:
					chooseLevelTwo();
					break;
				case GUI_ID_BUTTON_GAME_LEVEL_THREE:
					chooseLevelThree();
					break;

				case GUI_ID_BUTTON_SAVE_GAME_YES:
					chooseSaveGame();
					break;

				case GUI_ID_BUTTON_SAVE_GAME_NO:
					chooseNotSaveGame();
					break;

				case GUI_ID_BUTTON_SET_IP:
					webSet();
					break;

				case GUI_ID_QUIT_BUTTON:
					Context.device->closeDevice();
					break;

				case GUI_ID_NEW_WINDOW_BUTTON:
					{
						Context.listbox->addItem(L"Window created");
						Context.counter += 30;
						if (Context.counter > 200)
							Context.counter = 0;

						IGUIWindow* window = env->addWindow(
							rect<s32>(100 + Context.counter, 100 + Context.counter,
							300 + Context.counter, 200 + Context.counter),
							false, // modal?
							L"Test window");

						env->addStaticText(L"Please close me",
							rect<s32>(35,35,140,50),
							true, // border?
							false, // wordwrap?
							window);
					}
					return true;

				case GUI_ID_FILE_OPEN_BUTTON:
					Context.listbox->addItem(L"File open");
					env->addFileOpenDialog(L"Please choose a file.");
					return true;

				case GUI_ID_BUTTON_OPEN_MODEL:
					env->addFileOpenDialog(L"Please select a model file to open");
					break;
				case GUI_ID_BUTTON_SHOW_ABOUT:
					showAboutText();
					break;
				case GUI_ID_BUTTON_SHOW_TOOLBOX:
					createToolBox();
					break;
				case GUI_ID_BUTTON_CHAT_SENT:
					SendMessage = true;
					//sentChatText();
					break;
				default:
					return false;
				}
				break;

			default:
				break;
			}
		}

		return false;
	}

EventReceiver::showGameRecord()
{
	ifstream ifileWin("Winning Record.txt");
	ifstream ifileLose("Losing Record.txt");
	ifstream ifileTie("Tie Record.txt");
	/*int wintime = 0;
	int losetime = 0;
	int tietime = 0;
	ifileTie>>tietime;
	ifileWin>>wintime;
	ifileLose>>losetime;*/
	std::string winstr;
	std::string losestr;
	std::string tiestr;
	getline(ifileWin,winstr);
	getline(ifileLose,losestr);
	getline(ifileTie,tiestr);
	/*winstr = itoa(wintime);
	losestr = itoa(lostime);
	tiestr = itoa(tietime);*/
	char* winchar = (char*)winstr.c_str();
	char* losechar = (char*)losestr.c_str();
	char* tiechar = (char* )tiestr.c_str();
	wchar_t* winbuffer;
	wchar_t* losebuffer;
	wchar_t* tiebuffer;
	if(winchar)
	{
		size_t nu = strlen(winchar);
		size_t n =(size_t)MultiByteToWideChar(CP_ACP,0,(const char *)winchar,int(nu),NULL,0);
		winbuffer=0;
		winbuffer = new wchar_t[n+1];
		//if(n>=len) n=len-1;
		MultiByteToWideChar(CP_ACP,0,(const char *)winchar,int(nu),winbuffer,int(n));    
	}
	if(losechar)
	{
		size_t nu = strlen(losechar);
		size_t n =(size_t)MultiByteToWideChar(CP_ACP,0,(const char *)losechar,int(nu),NULL,0);
		losebuffer=0;
		losebuffer = new wchar_t[n+1];
		//if(n>=len) n=len-1;
		MultiByteToWideChar(CP_ACP,0,(const char *)losechar,int(nu),losebuffer,int(n));    
	}
	if(tiechar)
	{
		size_t nu = strlen(tiechar);
		size_t n =(size_t)MultiByteToWideChar(CP_ACP,0,(const char *)tiechar,int(nu),NULL,0);
		tiebuffer=0;
		tiebuffer = new wchar_t[n+1];
		//if(n>=len) n=len-1;
		MultiByteToWideChar(CP_ACP,0,(const char *)tiechar,int(nu),tiebuffer,int(n));    
	}
	Context.device->getGUIEnvironment()->addMessageBox(
		L"Winning Times:",winbuffer,false);
	Context.device->getGUIEnvironment()->addMessageBox(
		L"Losing Times:",losebuffer,false);
	Context.device->getGUIEnvironment()->addMessageBox(
		L"Tie Times:",tiebuffer,false);
}
EventReceiver::SaveGameSubWindow()
{
	IGUIEnvironment* env = Context.device->getGUIEnvironment();
	IGUIElement* root = env->getRootGUIElement();
	IGUIElement* e = root->getElementFromId(GUI_ID_SAVE_DIALOG_ROOT_WINDOW,true);
	if(e)
		e->remove();

	IGUIWindow* wnd = env->addWindow(core::rect<s32>(200,90,400,400),
		false,L"Save Game?",0,GUI_ID_SAVE_DIALOG_ROOT_WINDOW);
	IGUITabControl* tab_ip = env->addTabControl(
		core::rect<s32>(2,20,400,290),wnd,true,true);
	//IGUITabControl* tab_image = env->addTabControl(
	//	core::rect<s32>(20,20,400,290),wnd,true,true);
	IGUITab* t1 = tab_ip->addTab(L"Save Game");
	//IGUITab* t2 = tab_image->addTab(L"Image Setting");
	env->addStaticText(L"Save Unfinished GAME?",
		core::rect<s32>(2,20,400,50),true,false,t1);
	env->addButton(rect<s32>(2,90,100,120),t1,GUI_ID_BUTTON_SAVE_GAME_YES,L"Yes");
	env->addButton(rect<s32>(102,90,200,120),t1,GUI_ID_BUTTON_SAVE_GAME_NO,L"No!");

	root->bringToFront(root->getElementFromId(666,true));
}

EventReceiver::showWebSetWindow()
{
	Context.device->getGUIEnvironment()->addButton(rect<s32>(600+550,580,600+650,100+500), 0, GUI_ID_BUTTON_CHAT_SENT,L"SENT");
	IGUIElement* temp = Context.device->getGUIEnvironment()->getRootGUIElement()->getElementFromId(GUI_ID_CHAT_SENT_BOX);
	temp->setVisible(true);
	temp = Context.device->getGUIEnvironment()->getRootGUIElement()->getElementFromId(GUI_ID_CHAT_SENT_BOX);
	temp->setVisible(true);
	Context.device->getGUIEnvironment()->addButton(rect<s32>(600+550,549,600+650,560),0,GUI_ID_BUTTON_ONLINE_GAME_SIDE_BLACK,L"sel B");
	temp = Context.device->getGUIEnvironment()->getRootGUIElement()->getElementFromId(GUI_ID_BUTTON_ONLINE_GAME_SIDE_BLACK);
	temp->setVisible(true);
	IGUIEnvironment* env = Context.device->getGUIEnvironment();
	IGUIElement* root = env->getRootGUIElement();
	IGUIElement* e = root->getElementFromId(GUI_ID_DIALOG_ROOT_WINDOW,true);
	if(e)
		e->remove();

	IGUIWindow* wnd = env->addWindow(core::rect<s32>(200,90,400,400),
		false,L"Web Setting",0,GUI_ID_DIALOG_ROOT_WINDOW);
	IGUITabControl* tab_ip = env->addTabControl(
		core::rect<s32>(2,20,400,290),wnd,true,true);
	//IGUITabControl* tab_image = env->addTabControl(
	//	core::rect<s32>(20,20,400,290),wnd,true,true);
	IGUITab* t1 = tab_ip->addTab(L"IP Setting");
	//IGUITab* t2 = tab_image->addTab(L"Image Setting");
	env->addStaticText(L"Player 2 IP:",
		core::rect<s32>(2,20,400,50),true,false,t1);
	env->addEditBox(L"",core::rect<s32>(2,60,400,80),true,t1,GUI_ID_IP_INPUT);
	env->addButton(rect<s32>(2,90,200,120),t1,GUI_ID_BUTTON_SET_IP,L"Set Web");
	ipstr = root->getElementFromId(GUI_ID_IP_INPUT,true)->getText();//set ipstr
	if(ipstr.size() != 0)
		PlayOnLineGame = true;
	root->bringToFront(root->getElementFromId(666,true));
}

EventReceiver::webSet()
{
	IGUIEnvironment* env = Context.device->getGUIEnvironment();
	IGUIElement* root = env->getRootGUIElement();
	ipstr = root->getElementFromId(GUI_ID_IP_INPUT,true)->getText();
	if(ipstr.size() == 0)
	{
		env->addMessageBox(L"Warning",L"Empty IP address",true);
		return;
	}
	PlayOnLineGame = true;
	//int size = 0;
	//char* ipadd;
	//size = WideCharToMultiByte(CP_ACP,0,ipstr.c_str(),-1,NULL
	//	,0,NULL,NULL);
	//ipadd = (char*)malloc(size + 1);
	//WideCharToMultiByte(CP_ACP,0,ipstr.c_str(),-1,ipadd,
	//	size,NULL,NULL);
	//WSADATA wsaData;

	//int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);

	//if (iResult != NO_ERROR)
	//	env->addMessageBox(L"Warning!",L"Client: Error at WSAStartup().\n",false);
	//   //printf("Client: Error at WSAStartup().\n");

	//else
	//	env->addMessageBox(L"Warning!",L"Client: WSAStartup() is OK.\n",false);
	////printf("Client: WSAStartup() is OK.\n");
	//// Create a SOCKET for connecting to server

	//ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

	//if (ConnectSocket == INVALID_SOCKET)
	//{
	//	//printf("Client: Error at socket(): %ld.\n", WSAGetLastError());
	//	WSACleanup();
	////	return 0;
	//}
	////else
	////printf("Client: socket() is OK.\n");
	//// The sockaddr_in structure specifies the address family,
	//// IP address, and port of the server to be connected to.

	//sockaddr_in clientService;
	//clientService.sin_family = AF_INET;
	//clientService.sin_addr.s_addr = inet_addr(ipadd);
	//clientService.sin_port = htons(200);
	//// Connect to server.

	//if (connect(ConnectSocket, (SOCKADDR*)&clientService, sizeof(clientService)) == SOCKET_ERROR)
	//{
	//	env->addMessageBox(L"Warning!",L"Client: Failed to connect.\n",false);
	//	//printf("Client: Failed to connect.\n");
	//	WSACleanup();
	////	return 0;
	//}
	////////////////////////////////////////////////////////////////////////////////
	//core::stringw ChatText;
	//ChatText = root->getElementFromId(GUI_ID_CHAT_SENT_BOX,true)->getText();
	//root->getElementFromId(GUI_ID_CHAT_SENT_BOX,true)->setText(L"");
	//io::IXMLWriter* xmlWriter = Context.device->getFileSystem()->createXMLWriter(L"Chat Text.xml");
	//xmlWriter->writeText((wchar_t*)ChatText.c_str());
	//xmlWriter->drop();
	//int bytesSent;
	//int bytesRecv = SOCKET_ERROR;
	//char* sendbuf = "";
	//int size2;
	//size2 = WideCharToMultiByte(CP_ACP,0,ChatText.c_str(),-1
	//	,NULL,0,NULL,NULL);
	//sendbuf = (char*)malloc((size2 + 1)/**sizeof(char)*/);
	//WideCharToMultiByte(CP_ACP,0,ChatText.c_str(),-1,sendbuf,
	//	size2,NULL,NULL);
	//char recvbuf[100] = "";
//      core::stringw recvstr;
	//while(bytesRecv == SOCKET_ERROR )
	//{
	//	bytesRecv = recv(ConnectSocket, recvbuf, 100, 0);
	//	recvstr = recvbuf;
	//	if (bytesRecv == 0 || bytesRecv == WSAECONNRESET)
	//	{
	//		env->addMessageBox(L"Warning!",L"Client: Connection Closed.\n",false);
	//	 // printf("Client: Connection Closed.\n");
	//	  break;
	//	}
	////else
	////{
	//  // printf("Client: recv() is OK.\n");
	// //  printf("Client: Bytes received: %ld\n", bytesRecv);
	////}
	//}
	//// Send and receive data.
	//bytesSent = send(ConnectSocket, sendbuf, strlen(sendbuf), 0);
	//env->addMessageBox(L"Message sent",(wchar_t*)ChatText.c_str(),false);
	//env->addMessageBox(L"Message recv",(wchar_t*)recvstr.c_str(),false);
	////printf("Client: Bytes sent: %ld\n", bytesSent);
	//WSACleanup();
	////else
	////printf("Client: connect() is OK.\n");
	//


}

EventReceiver::gameLevelSelect()
{
	IGUIEnvironment* env = Context.device->getGUIEnvironment();
	IGUIElement* root = env->getRootGUIElement();
	IGUIElement* e = root->getElementFromId(GUI_ID_DIALOG_ROOT_WINDOW,true);
	if(e)
		e->remove();

	IGUIWindow* wnd = env->addWindow(core::rect<s32>(600,45,1000,480),
		false,L"Game Level Select",0,GUI_ID_DIALOG_ROOT_WINDOW);

	IGUITabControl* tab = env->addTabControl(
		core::rect<s32>(2,20,1200-602,480-7),wnd,true,true);

	IGUITab* t1 = tab->addTab(L"Level Select");
	env->addButton(rect<s32>(2,40,200,60),t1,GUI_ID_BUTTON_GAME_LEVEL_ONE,L"LEVEL ONE");
	env->addButton(rect<s32>(2,70,200,90),t1,GUI_ID_BUTTON_GAME_LEVEL_TWO,L"LEVEL TWO");
	env->addButton(rect<s32>(2,100,200,120),t1,GUI_ID_BUTTON_GAME_LEVEL_THREE,L"LEVEL THREE");
	root->bringToFront(root->getElementFromId(666,true));
}

EventReceiver::createToolBox()
{
	IGUIEnvironment* env = Context.device->getGUIEnvironment();
	IGUIElement* root = env->getRootGUIElement();
	IGUIElement* e = root->getElementFromId(GUI_ID_DIALOG_ROOT_WINDOW,true);
	if(e)
		e->remove();

	IGUIWindow* wnd = env->addWindow(core::rect<s32>(600,45,800,480),
		false,L"Toolset",0,GUI_ID_DIALOG_ROOT_WINDOW);

	IGUITabControl* tab = env->addTabControl(
		core::rect<s32>(2,20,800-602,480-7),wnd,true,true);

	IGUITab* t1 = tab->addTab(L"Skin");

	env->addStaticText(L"GUI Transp:",
		core::rect<s32>(10,20,200,55), true, false, t1);
	IGUIScrollBar* scrollbar = env->addScrollBar(true,
		core::rect<s32>(10,55,200,75),t1,GUI_ID_TRANSPARENCY_SCROLL_BAR);
	scrollbar->setMax(255);
	scrollbar->setPos(255);

	env->addStaticText(L"GUI Red:",
		core::rect<s32>(10,85,150,120), true, false, t1);
	IGUIScrollBar* scrollbar_red = env->addScrollBar(true,
		core::rect<s32>(10,125,200,145),t1,GUI_ID_COLOR_SCROLL_BAR_RED);
	scrollbar_red->setMax(255);
	scrollbar_red->setPos(255);

	env->addStaticText(L"GUI Green:",
		core::rect<s32>(10,155,150,190), true, false, t1);
	IGUIScrollBar* scrollbar_green = env->addScrollBar(true,
		core::rect<s32>(10,195,200,215),t1,GUI_ID_COLOR_SCROLL_BAR_GREEN);
	scrollbar_green->setMax(255);
	scrollbar_green->setPos(255);

	env->addStaticText(L"GUI Blue:",
		core::rect<s32>(10,225,150,260), true, false, t1);
	IGUIScrollBar* scrollbar_blue = env->addScrollBar(true,
		core::rect<s32>(10,265,200,285),t1,GUI_ID_COLOR_SCROLL_BAR_BLUE);
	scrollbar_blue->setMax(255);
	scrollbar_blue->setPos(255);

	root->bringToFront(root->getElementFromId(666,true));
}